package com.chen.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.common.Result;
import com.chen.mapper.InfoMapper;
import com.chen.mapper.PermissionMapper;
import com.chen.mapper.RoleMapper;
import com.chen.mapper.UserMapper;
import com.chen.pojo.*;
import com.chen.pojo.bean.UserInfo;
import com.chen.service.LoginService;
import com.chen.utils.IpUtils;
import com.chen.utils.MD5Utils;
import com.chen.utils.TokenUtils;

import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author chenchao

 */
@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private InfoMapper infoMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private PermissionMapper permissionMapper;


    @Resource
    private HttpServletRequest request;


    //登录
    public Result<UserInfo> login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("password", MD5Utils.md5(user.getPassword()));
        System.out.println(user.getPassword());
        System.out.println(MD5Utils.md5(user.getPassword()));
        User res = userMapper.selectOne(queryWrapper);

        List<Info> selectList = infoMapper.selectList(null);


        if (res == null) {
            return Result.error(-1, "用户名或密码错误");
        }

        String token = TokenUtils.genToken(res.getId().toString(), res.getPassword());
        res.setToken(token);

        selectList.stream().filter(m -> m.getUsername().equals(user.getUsername())).forEach(n -> res.setEnable(n.getEnable()));

        if (ObjectUtil.isNotEmpty(res)) {
            if (res.getEnable() == false) {
                return Result.error(-3, "该账号涉嫌违法，已被冻结");
            }
        }


//        存储登录信息
        Info message = new Info();
        List<Info> infoList = infoMapper.selectList(null);
        Stream<Info> stream = infoList.stream();
//        判断2个表中是否有相同的用户名 如果有就进行更新操作，反之插入
        boolean anyMatch = stream.anyMatch(s -> s.getUsername().equals(res.getUsername()));

//插入
        if (!anyMatch) {
            String ipAddress = IpUtils.getIpAddress(request);
            String ipSource = IpUtils.getIpSource(ipAddress);
            String type = IpUtils.getUserAgent(request).toString();
            message.setType(type);
            message.setUsername(res.getUsername());
            message.setEnable(true);
            message.setIp(ipAddress);  //ip
            message.setAddr(ipSource);  //城市名
            message.setTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));//创建时间
            infoMapper.insert(message);
        }
//        更新
        else {
            Info selectOne = new Info();
            List<User> userList = userMapper.selectList(null);
//            寻找出需要更新的用户的id
            selectOne = infoMapper.selectOne(Wrappers.<Info>lambdaQuery().eq(Info::getUsername, res.getUsername()));
            if (ObjectUtil.isNotEmpty(selectOne)) {
                if (StrUtil.isNotBlank(selectOne.getUsername())) {
                    message.setId(selectOne.getId());

                }
            }


            message.setId(selectOne.getId());
            String ipAddress = IpUtils.getIpAddress(request);
            String ipSource = IpUtils.getIpSource(ipAddress);
            String type = IpUtils.getUserAgent(request).toString();
            message.setType(type);
            message.setIp(ipAddress);  //ip
            message.setAddr(ipSource);  //城市名
            message.setLastTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); //创建时间
            infoMapper.updateById(message);
        }
        String userId = request.getHeader("X-ID");
        System.out.println(userId);
        HashSet<Permission> permissionSet = new HashSet<>();
        //从user_role中通过用户id查询所有的角色信息

        List<UserRole> userRoles = roleMapper.getByUserRoleUserId(res.getId());
        List<Permission> permissions=new ArrayList<>();

        for (UserRole userRole : userRoles) {
            //根据roleId从role_permission表查询出所有的permissionId
            List<RolePermisson> rolePermissions = permissionMapper.getRolePermissionByRoleId(userRole.getRoleId());
            for (RolePermisson rolePermission : rolePermissions) {
                int permissionId = rolePermission.getPermissionId();
                //根据permissionId查询permission信息
                Permission permission = permissionMapper.selectById(permissionId);
                permissionSet.add(permission);
            }
        }

        // 对资源根据id进行排序
        LinkedHashSet<Permission> sortedSet = permissionSet.stream().sorted(Comparator.comparing(Permission::getId)).collect(Collectors.toCollection(LinkedHashSet::new));

        res.setPermissions(sortedSet);
        UserInfo info = new UserInfo(res);
        System.out.println(info);
        return Result.success(info);
    }

    public Result<UserInfo> login(Integer id) {
        User res = userMapper.selectById(id);

        List<Info> selectList = infoMapper.selectList(null);


        if (res == null) {
            return Result.error(-1, "当前用户不存在");
        }

        String token = TokenUtils.genToken(res.getId().toString(), res.getPassword());
        res.setToken(token);

        selectList.stream().filter(m -> m.getUsername().equals(res.getUsername())).forEach(n -> res.setEnable(n.getEnable()));

//        if (ObjectUtil.isNotEmpty(res)) {
//            if (res.getEnable() == false) {
//                return Result.error(-3, "该账号涉嫌违法，已被冻结");
//            }
//        }


//        存储登录信息
        Info message = new Info();
        List<Info> infoList = infoMapper.selectList(null);
        Stream<Info> stream = infoList.stream();
//        判断2个表中是否有相同的用户名 如果有就进行更新操作，反之插入
        boolean anyMatch = stream.anyMatch(s -> s.getUsername().equals(res.getUsername()));

//插入
        if (!anyMatch) {
            String ipAddress = IpUtils.getIpAddress(request);
            String ipSource = IpUtils.getIpSource(ipAddress);
            String type = IpUtils.getUserAgent(request).toString();
            message.setType(type);
            message.setUsername(res.getUsername());
            message.setEnable(true);
            message.setIp(ipAddress);  //ip
            message.setAddr(ipSource);  //城市名
            message.setTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));//创建时间
            infoMapper.insert(message);
        }
//        更新
        else {
            Info selectOne = new Info();
            List<User> userList = userMapper.selectList(null);
//            寻找出需要更新的用户的id
            selectOne = infoMapper.selectOne(Wrappers.<Info>lambdaQuery().eq(Info::getUsername, res.getUsername()));
            if (ObjectUtil.isNotEmpty(selectOne)) {
                if (StrUtil.isNotBlank(selectOne.getUsername())) {
                    message.setId(selectOne.getId());

                }
            }


            message.setId(selectOne.getId());
            String ipAddress = IpUtils.getIpAddress(request);
            String ipSource = IpUtils.getIpSource(ipAddress);
            String type = IpUtils.getUserAgent(request).toString();
            message.setType(type);
            message.setIp(ipAddress);  //ip
            message.setAddr(ipSource);  //城市名
            message.setLastTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")); //创建时间
            infoMapper.updateById(message);
        }
        String userId = request.getHeader("X-ID");
        System.out.println(userId);
        HashSet<Permission> permissionSet = new HashSet<>();
        //从user_role中通过用户id查询所有的角色信息

        List<UserRole> userRoles = roleMapper.getByUserRoleUserId(res.getId());
        List<Permission> permissions=new ArrayList<>();

        for (UserRole userRole : userRoles) {
            //根据roleId从role_permission表查询出所有的permissionId
            List<RolePermisson> rolePermissions = permissionMapper.getRolePermissionByRoleId(userRole.getRoleId());
            for (RolePermisson rolePermission : rolePermissions) {
                int permissionId = rolePermission.getPermissionId();
                //根据permissionId查询permission信息
                Permission permission = permissionMapper.selectById(permissionId);
                permissionSet.add(permission);
            }
        }

        // 对资源根据id进行排序
        LinkedHashSet<Permission> sortedSet = permissionSet.stream().sorted(Comparator.comparing(Permission::getId)).collect(Collectors.toCollection(LinkedHashSet::new));

        res.setPermissions(sortedSet);
        UserInfo info = new UserInfo(res);
        System.out.println(info);
        return Result.success(info);
    }
    //注册
    public Result<?> register(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error(-2, "用户已存在");
        }

        if (!user.getCode().equals(MailService.codes)) {
            return Result.error(-1, "验证码错误");
        }

        Date date = new Date();
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        user.setRegtime(format);
        user.setAge(18);
        user.setSex("未知");
        user.setAddress("地球");
        user.setNick("ヅ記憶丶锝浅笑");
        user.setPassword(MD5Utils.md5(user.getPassword()));

        user.setAvatar("https://img1.baidu.com/it/u=4169370716,188510386&fm=253&fmt=auto&app=138&f=JPEG?w=224&h=223");
        Info message = new Info();
        String ipAddress = IpUtils.getIpAddress(request);
        String ipSource = IpUtils.getIpSource(ipAddress);
        String type = IpUtils.getUserAgent(request).toString();
        message.setType(type);
        message.setUsername(user.getUsername());
        message.setEnable(true);
        message.setIp(ipAddress);  //ip
        message.setAddr(ipSource);  //城市名
        message.setTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));//创建时间
        infoMapper.insert(message);

        userMapper.insert(user);


        return Result.success();
    }

    //忘记密码
    public Result<?> forget(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res == null) {
            return Result.error(-2, "用户不存在,请前往注册");
        }
        if (!user.getCode().equals(MailService.codes)) {
            return Result.error(-1, "验证码错误");
        }

        res.setUsername(user.getUsername());
//        res.setPassword(user.getPassword());
        res.setPassword(MD5Utils.md5(user.getPassword()));
        userMapper.updateById(res);
        return Result.success();
    }


    //注销
    public Result<?> logout(Long id) {
        return Result.success(userMapper.deleteById(id));
    }


    public User getOpenid(String openid) {
        return userMapper.getOpenid(openid);
    }

}
